/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package components;

import dao.PetDAO;
import entity.Appointment;
import entity.Pet;
import entity.Vaccine;
import hpvas.HPVAS;
import java.awt.Image;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Persistence;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Juan
 */
public class PPetDisplay extends javax.swing.JPanel {
    
    private Pet currentPet = null;
    private boolean changes = false;

    /**
     * Creates new form PPetRegistration
     */
    public PPetDisplay() {
        initComponents();
        initialize();
    }
    
    public PPetDisplay(Pet pet) {
        this.currentPet = pet;
        initComponents();
        initialize();
        LName.setText(pet.getName());
        LSpecies.setText(pet.getSpecies());
        LAge.setText(String.valueOf(pet.getAge()));
        LWeight.setText(String.valueOf(pet.getWeight()));
        ImageIcon picture = new ImageIcon(pet.getPicturePath());
        picture = new ImageIcon(picture.getImage().getScaledInstance(120, 120, Image.SCALE_DEFAULT));
        LPicture.setIcon(picture);
        LOwner.setText(pet.getOwner().toString());
        
        List<Appointment> appointments = pet.getMedicalRecord().getAppointments();
        DefaultTableModel appModel = (DefaultTableModel) TAppointments.getModel();
        for (Appointment appointment : appointments) {
            appModel.addRow(new Object[] {appointment.getAppointmentDate(),
                                       appointment.getCharge(),
                                       appointment.getNotes(),
                                       appointment.getVeterinarian()});
        }
        
        List<Vaccine> vaccines = pet.getMedicalRecord().getVaccines();
        DefaultTableModel model = (DefaultTableModel) TVaccines.getModel();
        for (Vaccine vaccine : vaccines) {
            model.addRow(new Object[] {vaccine.getName(), vaccine.getDosage()});
        }
    }
    
    
    public void save() {
        if (changes) {
            PetDAO petDAO = new PetDAO(Persistence.createEntityManagerFactory("HPVA"));
            currentPet.getMedicalRecord().setVaccines(collectVaccines());
            try {
                petDAO.edit(currentPet);
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this.getTopLevelAncestor(),
                        "There was an error saving the vaccines.", "Error", JOptionPane.ERROR_MESSAGE);
                System.err.println(ex.getMessage());
            }
        }
    }
    
    private List<Vaccine> collectVaccines() {
        List<Vaccine> vaccines = new ArrayList<>();
        DefaultTableModel model = (DefaultTableModel) TVaccines.getModel();
        for (int i = 0; i < model.getRowCount(); i++) {
            vaccines.add(new Vaccine((String) model.getValueAt(i, 0), (float) model.getValueAt(i, 1), currentPet.getMedicalRecord()));
        }
        return vaccines;
    }
    
    private void initialize() {
        TVaccines.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

            @Override
            public void valueChanged(ListSelectionEvent e) {
                if (e.getFirstIndex() != -1) {
                    BRemoveVaccine.setEnabled(true);
                } else {
                    BRemoveVaccine.setEnabled(false);
                }
            }
        });
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        LName = new javax.swing.JLabel();
        LSpecies = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        BEditPet = new javax.swing.JButton();
        BClose = new javax.swing.JButton();
        LAge = new javax.swing.JLabel();
        LWeight = new javax.swing.JLabel();
        LOwner = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        TAppointments = new javax.swing.JTable();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        TVaccines = new javax.swing.JTable();
        BAddVaccine = new javax.swing.JButton();
        BRemoveVaccine = new javax.swing.JButton();
        BRemovePet = new javax.swing.JButton();
        LPicture = new javax.swing.JLabel();

        LName.setText("Name");

        LSpecies.setText("Species:");

        jLabel4.setText("Age:");

        jLabel5.setText("Weight:");

        jLabel7.setText("Owner:");

        jLabel8.setText("Kg");

        BEditPet.setText("Edit Pet");
        BEditPet.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BEditPetActionPerformed(evt);
            }
        });

        BClose.setText("Close");
        BClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BCloseActionPerformed(evt);
            }
        });

        LAge.setText("jLabel1");

        LWeight.setText("jLabel1");

        LOwner.setForeground(new java.awt.Color(0, 0, 255));
        LOwner.setText("jLabel1");
        LOwner.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        LOwner.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                LOwnerMouseClicked(evt);
            }
        });

        jLabel1.setText("Appointments:");

        TAppointments.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Date", "Charge", "Notes", "Veterinarian"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(TAppointments);

        jLabel2.setText("Vaccines:");

        TVaccines.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Name", "Dosage"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.Float.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jScrollPane2.setViewportView(TVaccines);

        BAddVaccine.setText("Add Vaccine");
        BAddVaccine.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BAddVaccineActionPerformed(evt);
            }
        });

        BRemoveVaccine.setText("Remove Vaccine");
        BRemoveVaccine.setEnabled(false);
        BRemoveVaccine.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BRemoveVaccineActionPerformed(evt);
            }
        });

        BRemovePet.setText("Delete Pet");
        BRemovePet.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BRemovePetActionPerformed(evt);
            }
        });

        LPicture.setMinimumSize(new java.awt.Dimension(120, 120));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(LPicture, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(LName)
                            .addComponent(LSpecies)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel7)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(LOwner))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel4)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(LAge))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel5)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(LWeight)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel8))
                            .addComponent(jLabel1)
                            .addComponent(jLabel2)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(BAddVaccine)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(BRemoveVaccine))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(BClose)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(BEditPet)
                                .addGap(18, 18, 18)
                                .addComponent(BRemovePet)))
                        .addGap(0, 135, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(LName)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(LPicture, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(LSpecies)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(LAge))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(LWeight)
                    .addComponent(jLabel8))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(LOwner))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 161, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(BAddVaccine)
                    .addComponent(BRemoveVaccine))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(BClose)
                    .addComponent(BEditPet)
                    .addComponent(BRemovePet))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void BCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BCloseActionPerformed
        save();
        HPVAS.closeCurrentTab();
    }//GEN-LAST:event_BCloseActionPerformed

    private void BEditPetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BEditPetActionPerformed
        save();
        HPVAS.editEntity(currentPet);
    }//GEN-LAST:event_BEditPetActionPerformed

    private void LOwnerMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_LOwnerMouseClicked
        HPVAS.displayEntity(currentPet.getOwner());
    }//GEN-LAST:event_LOwnerMouseClicked

    private void BRemovePetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BRemovePetActionPerformed
        HPVAS.deleteEntity(currentPet);
    }//GEN-LAST:event_BRemovePetActionPerformed

    private void BAddVaccineActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BAddVaccineActionPerformed
        DefaultTableModel model = (DefaultTableModel) TVaccines.getModel();
        model.addRow(new Object[] {"",0.0});
        changes = true;
    }//GEN-LAST:event_BAddVaccineActionPerformed

    private void BRemoveVaccineActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BRemoveVaccineActionPerformed
        int selectedRow = TVaccines.getSelectedRow();
        if (selectedRow != -1) {
            DefaultTableModel model = (DefaultTableModel) TVaccines.getModel();
            model.removeRow(selectedRow);
            TVaccines.getSelectionModel().setSelectionInterval(selectedRow -1, selectedRow - 1);
            if (selectedRow == 0) {
                BRemoveVaccine.setEnabled(false);
            }
            changes = true;
        }
    }//GEN-LAST:event_BRemoveVaccineActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton BAddVaccine;
    private javax.swing.JButton BClose;
    private javax.swing.JButton BEditPet;
    private javax.swing.JButton BRemovePet;
    private javax.swing.JButton BRemoveVaccine;
    private javax.swing.JLabel LAge;
    private javax.swing.JLabel LName;
    private javax.swing.JLabel LOwner;
    private javax.swing.JLabel LPicture;
    private javax.swing.JLabel LSpecies;
    private javax.swing.JLabel LWeight;
    private javax.swing.JTable TAppointments;
    private javax.swing.JTable TVaccines;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    // End of variables declaration//GEN-END:variables
}
